package cn.sciento.core.jackson.deserializer;

import cn.sciento.core.jackson.annotation.IgnoreTimeZone;
import cn.sciento.core.oauth.CustomUserDetails;
import cn.sciento.core.oauth.DetailsHelper;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class DateDeserializer extends JsonDeserializer<Date> implements ContextualDeserializer {
    private static final Logger LOGGER = LoggerFactory.getLogger(DateDeserializer.class);

    private boolean ignoreTimeZone = false;

    public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        try {
            SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (this.ignoreTimeZone)
                return dateFormatGmt.parse(jsonParser.getValueAsString());
            CustomUserDetails details = DetailsHelper.getUserDetails();
            if (details != null && details.getTimeZone() != null)
                dateFormatGmt.setTimeZone(TimeZone.getTimeZone(details.getTimeZone()));
            return dateFormatGmt.parse(jsonParser.getValueAsString());
        } catch (Exception e) {
            LOGGER.warn("date format error : {}", e);
            return null;
        }
    }

    public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) {
        return (new DateDeserializer()).setIgnoreTimeZone(property.getMember().hasAnnotation(IgnoreTimeZone.class));
    }

    private DateDeserializer setIgnoreTimeZone(boolean ignoreTimeZone) {
        this.ignoreTimeZone = ignoreTimeZone;
        return this;
    }
}
